package com.travel.service.impl.Auth;

import com.travel.exception.BadRequestException;
import com.travel.mapper.admin.AdminMapper;
import com.travel.mapper.user.UserMapper;
import com.travel.model.dto.auth.*;
import com.travel.model.entity.auth.Admin;
import com.travel.model.entity.auth.User;
import com.travel.security.jwt.JwtUtils;
import com.travel.service.Service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
//认证服务实现类 用户登录 管理员登录 用户注册 修改密码
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserMapper userMapper;
    private final AdminMapper adminMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtils jwtUtils;

    @Override
    public JwtResponse login(LoginRequest loginRequest) {
        // 1. 查找用户
        User user = userMapper.findByUsername(loginRequest.getUsername())
            .orElseThrow(() -> new BadRequestException("用户不存在"));
            
        // 2. 验证密码
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new BadRequestException("密码错误");
        }

        if (user.getStatus() != 1) {
            throw new BadRequestException("用户已被禁用");
        }

        // 3. 生成 JWT
        String jwt = jwtUtils.generateToken(user.getUsername(), "ROLE_USER");
        
        // 4. 返回响应
        return new JwtResponse(jwt, user.getId(), user.getUsername(), user.getEmail(), List.of("USER"));
    }

    @Override
    public JwtResponse adminLogin(AdminLoginRequest loginRequest) {
        try {
            // 1. 查找管理员
            Admin admin = adminMapper.findByUsername(loginRequest.getUsername());
            if (admin == null) {
                throw new BadRequestException("管理员账号不存在");
            }

            if (admin.getStatus() != 1) {
                throw new BadRequestException("管理员账号已被禁用");
            }

            // 2. 验证密码
            if (!passwordEncoder.matches(loginRequest.getPassword(), admin.getPassword())) {
                throw new BadRequestException("密码错误");
            }

            // 3. 生成 JWT
            String jwt = jwtUtils.generateToken(admin.getUsername(), "ROLE_ADMIN");
            
            // 4. 返回响应
            return new JwtResponse(
                jwt,
                admin.getId(),
                admin.getUsername(),
                admin.getEmail(),
                List.of("ADMIN")
            );
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }

    @Override
    @Transactional
    public void register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userMapper.existsByUsername(request.getUsername())) {
            throw new BadRequestException("用户名已被使用");
        }
        
        // 检查邮箱是否已存在
        if (userMapper.existsByEmail(request.getEmail())) {
            throw new BadRequestException("邮箱已被注册");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setNickname(request.getNickname());
        user.setAvatar(request.getAvatar());
        user.setStatus(1);
        user.setCreatedTime(LocalDateTime.now());
        
        // 保存用户并检查结果
        int result = userMapper.insert(user);
        if (result != 1) {
            throw new BadRequestException("用户注册失败");
        }
    }

    @Override
    public void changePassword(PasswordChangeRequest request) {
        // 1. 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new BadRequestException("用户未登录");
        }
        
        String username = authentication.getName();
        User user = userMapper.findByUsername(username)
            .orElseThrow(() -> new BadRequestException("用户不存在"));

        // 2. 验证原密码
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            throw new BadRequestException("原密码错误");
        }

        // 3. 更新新密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        user.setUpdatedTime(LocalDateTime.now());
        
        // 4. 保存到数据库
        userMapper.update(user);
    }
}